package net

import (
	"net"
	"syscall"
)

func GetAddr(fd int) net.Addr {
	addr, err := syscall.Getpeername(fd)
	if err != nil {
		return nil
	}

	switch sa := addr.(type) {
	case *syscall.SockaddrInet4:
		return &net.TCPAddr{
			IP:   net.IPv4(sa.Addr[0], sa.Addr[1], sa.Addr[2], sa.Addr[3]),
			Port: int(sa.Port),
		}
	case *syscall.SockaddrInet6:
		return &net.TCPAddr{
			IP:   net.IP(sa.Addr[:]),
			Port: int(sa.Port),
		}
	}
	return nil
}

func GetIPFromIpPort(ipPort string) string {
	ip, _, err := net.SplitHostPort(ipPort)
	if err != nil {
		return ""
	}
	return ip
}
